﻿using FluentMigrator;

namespace Rubikev.Rockface.Database.ForeignKeys
{
   /// <summary>
   /// Base class for creating foreign keys
   /// </summary>
   public abstract class CreateForeignKeyMigration : Migration
   {
      /// <summary>
      /// The name of the foreign key to create: FK_<see cref="FromTableName"/><see cref="ToTableName"/>_<see cref="ToTableName"/>
      /// </summary>
      public string ForeignKeyName { get { return string.Format("FK_{0}{1}_{1}", FromTableName, ToTableName); } }

      /// <summary>
      /// The name of the table the key is from
      /// </summary>
      public abstract string FromTableName { get; }

      /// <summary>
      /// The name of the table the key is to
      /// </summary>
      public abstract string ToTableName { get; }

      /// <summary>
      /// The name of the column the key is from. Override if it isn't in the format <see cref="ToTableName"/>Id
      /// </summary>
      public virtual string FromTableColumn { get { return string.Format("{0}Id", ToTableName);} }

      /// <summary>
      /// The name of the column the key is to. Override if it isn't 'Id'
      /// </summary>
      public virtual string ToTableColumn { get {return "Id";} }

      /// <summary>
      /// Creates the foreign key
      /// </summary>
      public override void Up()
      {
         Create.ForeignKey(ForeignKeyName)
            .FromTable(FromTableName).ForeignColumn(FromTableColumn)
            .ToTable(ToTableName).PrimaryColumn(ToTableColumn);
      }

      /// <summary>
      /// Drops the foreign key
      /// </summary>
      public override void Down()
      {
         Delete.ForeignKey(ForeignKeyName).OnTable(FromTableName);
      }
   }
}
